const productData = [
    {商品ID: 945, 商品名称: 'UR2024夏季新款女装复古纯欲氛围感一字肩短款T恤衫UWG440060', 商品类型: '普通商品', 商品售价: '193.00', 销量: 310, 库存: 1967, 排序: 9999, 状态: true},
    {商品ID: 963, 商品名称: 'FOMIX 蛋壳椅 进口头层牛皮橙色单人沙发椅Egg chair设计师蛋椅', 商品类型: '普通商品', 商品售价: '1204.00', 销量: 179, 库存: 1467, 排序: 9999, 状态: true},
    {商品ID: 108, 商品名称: '阿迪达斯官网 adidas BBALL CAP COT 男女训练运动帽子FQ5270', 商品类型: '普通商品', 商品售价: '589.00', 销量: 554, 库存: 3567, 排序: 9981, 状态: false},
    {商品ID: 48, 商品名称: '真力时（ZENITH）瑞士手表DEFY系列CLASSIC经典腕表男士镂空机械腕表', 商品类型: '普通商品', 商品售价: '254.00', 销量: 234, 库存: 2247, 排序: 9963, 状态: true},
    {商品ID: 911, 商品名称: '劳伦斯意式极简大平层设计师款直排真皮沙发简约客厅别墅大小户型', 商品类型: '普通商品', 商品售价: '85.00', 销量: 540, 库存: 1573, 排序: 9921, 状态: true},
    {商品ID: 934, 商品名称: '松典数码相机5K微单复古女学生入门级高清旅游专用vlog摄影照相机', 商品类型: '普通商品', 商品售价: '342.00', 销量: 664, 库存: 7325, 排序: 9900, 状态: false},
    {商品ID: 1005, 商品名称: 'HEFANG何方珠宝编织小方糖项链轻奢简约饰品生日礼物', 商品类型: '普通商品', 商品售价: '632.00', 销量: 965, 库存: 1673, 排序: 9984, 状态: true},
    {商品ID: 1006, 商品名称: '劳伦斯意式极简大平层设计师款直排真皮沙发简约客厅别墅大小户型', 商品类型: '普通商品', 商品售价: '245.00', 销量: 367, 库存: 2267, 排序: 9978, 状态: true},
    {商品ID: 938, 商品名称: 'iKF M5复古无线蓝牙K歌音响户外音箱话筒麦克风家用2024新款送礼', 商品类型: '普通商品', 商品售价: '146.00', 销量: 226, 库存: 1967, 排序: 9912, 状态: false},
    {商品ID: 921, 商品名称: 'TonymolyTONYMOLY托尼魅力唯我闪耀胶原光感气垫保湿遮瑕粉底bb霜', 商品类型: '普通商品', 商品售价: '643.00', 销量: 774, 库存: 4950, 排序: 9908, 状态: true},
    {商品ID: 572, 商品名称: 'UR2024夏季新款女装复古纯欲氛围感一字肩短款T恤衫UWG440060', 商品类型: '普通商品', 商品售价: '563.00', 销量: 368, 库存: 3985, 排序: 9921, 状态: true},
    {商品ID: 275, 商品名称: '圣诞节生日礼物女生送给闺蜜女朋友老师实用的高级感伴手礼品小众', 商品类型: '普通商品', 商品售价: '533.00', 销量: 843, 库存: 4363, 排序: 9953, 状态: false},
    {商品ID: 24, 商品名称: '柏黛雅全套化妆刷套装眼影腮红修容刷子便携彩妆化妆工具官方正品', 商品类型: '普通商品', 商品售价: '635.00', 销量: 843, 库存: 7432, 排序: 9942, 状态: true},
    {商品ID: 98, 商品名称: '贝昂智能空气循环风扇家用落地电语音控制新款音静声轻室内ProMax', 商品类型: '普通商品', 商品售价: '267.00', 销量: 774, 库存: 2674, 排序: 9965, 状态: true},
    {商品ID: 901, 商品名称: '衣帽架卧室落地挂衣架网红置物架立式家用床边放衣服架子衣架神器', 商品类型: '普通商品', 商品售价: '632.00', 销量: 853, 库存: 7634, 排序: 9923, 状态: false},
    {商品ID: 912, 商品名称: '中国李宁盘古TREK凉鞋男女鞋2024新款夏季情侣透气低帮运动鞋', 商品类型: '普通商品', 商品售价: '742.00', 销量: 943, 库存: 8543, 排序: 9976, 状态: true},
    {商品ID: 55, 商品名称: '贝昂智能空气循环风扇家用落地电语音控制新款音静声轻室内ProMax', 商品类型: '普通商品', 商品售价: '734.00', 销量: 246, 库存: 8433, 排序: 9924, 状态: true},
    {商品ID: 924, 商品名称: 'CHICVEN「摩登工业」科技感反光渐变羽绒服立领面包服外套女冬季', 商品类型: '普通商品', 商品售价: '633.00', 销量: 534, 库存: 5763, 排序: 9975, 状态: false},
    {商品ID: 963, 商品名称: '【Gucci七夕礼物】GUCCI古驰倾色云雾唇釉哑光203 枫叶红棕蒸汽啵', 商品类型: '普通商品', 商品售价: '242.00', 销量: 556, 库存: 2657, 排序: 9986, 状态: true},
    {商品ID: 911, 商品名称: 'RALPH LAUREN【肖战同款】 拉夫劳伦地球系列 淡香氛 新年礼物', 商品类型: '普通商品', 商品售价: '143.00', 销量: 256, 库存: 2455, 排序: 9999, 状态: true}
];

const tbody = document.getElementById('productTableBody');
const searchInput = document.getElementById('searchInput');
const suggestionsContainer = document.getElementById('suggestionsContainer');
const paginationInfo = document.getElementById('paginationInfo');
const prevPageBtn = document.getElementById('prevPage');
const nextPageBtn = document.getElementById('nextPage');
const pageNumbersContainer = document.getElementById('pageNumbers');

let highlightedIndex = -1;
let currentPage = 1;
const itemsPerPage = 10;
let filteredProducts = [...productData];

// 渲染商品数据
function renderProducts(products, page = 1) {
    tbody.innerHTML = '';

    const startIndex = (page - 1) * itemsPerPage;
    const endIndex = startIndex + itemsPerPage;
    const paginatedProducts = products.slice(startIndex, endIndex);

    if (paginatedProducts.length === 0) {
        const tr = document.createElement("tr");
        const td = document.createElement("td");
        td.colSpan = 10;
        td.textContent = "没有找到匹配的商品";
        td.style.textAlign = "center";
        td.style.padding = "30px";
        td.style.color = "#909399";
        tr.appendChild(td);
        tbody.appendChild(tr);
        return;
    }

    paginatedProducts.forEach((product, index) => {
        const tr = document.createElement("tr");

        // 复选框
        const tdCheckbox = document.createElement("td");
        tdCheckbox.innerHTML = `<input type="checkbox" name="box[]">`;
        tr.appendChild(tdCheckbox);

        // 商品ID
        const tdId = document.createElement("td");
        tdId.textContent = product.商品ID;
        tr.appendChild(tdId);

        // 商品名称
        const tdName = document.createElement("td");
        tdName.innerHTML = `<span class="product-name" title="${product.商品名称}">${product.商品名称}</span>`;
        tr.appendChild(tdName);

        // 商品类型
        const tdType = document.createElement("td");
        tdType.textContent = product.商品类型;
        tr.appendChild(tdType);

        // 商品售价
        const tdPrice = document.createElement("td");
        tdPrice.innerHTML = `<span class="price">¥${product.商品售价}</span>`;
        tr.appendChild(tdPrice);

        // 销量
        const tdSales = document.createElement("td");
        tdSales.innerHTML = `<span class="sales">${product.销量}</span>`;
        tr.appendChild(tdSales);

        // 库存
        const tdStock = document.createElement("td");
        tdStock.innerHTML = `<span class="stock">${product.库存}</span>`;
        tr.appendChild(tdStock);

        // 排序
        const tdSort = document.createElement("td");
        tdSort.textContent = product.排序;
        tr.appendChild(tdSort);

        // 状态
        const tdStatus = document.createElement("td");
        tdStatus.innerHTML = `
                <label class="status-switch">
                    <input type="checkbox" ${product.状态 ? 'checked' : ''}>
                    <span class="slider"></span>
                </label>
            `;
        tr.appendChild(tdStatus);

        // 操作
        const tdAction = document.createElement("td");
        tdAction.innerHTML = `
                <div>
                    <button class="btn1">编辑</button>
                    <button class="btn2">删除</button>
                </div>
            `;
        tr.appendChild(tdAction);

        tbody.appendChild(tr);
    });

    // 更新分页信息
    updatePagination(products, page);
}

// 更新分页信息
function updatePagination(products, currentPage) {
    const totalItems = products.length;
    const totalPages = Math.ceil(totalItems / itemsPerPage);


    // 更新页码按钮
    pageNumbersContainer.innerHTML = '';

    // 显示最多5个页码按钮
    const maxVisiblePages = 2;
    let startPage = Math.max(1, currentPage - Math.floor(maxVisiblePages / 2));
    let endPage = Math.min(totalPages, startPage + maxVisiblePages - 1);

    if (endPage - startPage + 1 < maxVisiblePages) {
        startPage = Math.max(1, endPage - maxVisiblePages + 1);
    }

    // 第一页按钮
    if (startPage > 1) {
        const firstPageBtn = document.createElement('button');
        firstPageBtn.textContent = '1';
        firstPageBtn.addEventListener('click', () => goToPage(1));
        pageNumbersContainer.appendChild(firstPageBtn);

        if (startPage > 2) {
            const ellipsis = document.createElement('span');
            ellipsis.textContent = '...';
            pageNumbersContainer.appendChild(ellipsis);
        }
    }

    // 中间页码按钮
    for (let i = startPage; i <= endPage; i++) {
        const pageBtn = document.createElement('button');
        pageBtn.textContent = i;
        if (i === currentPage) {
            pageBtn.classList.add('active');
        }
        pageBtn.addEventListener('click', () => goToPage(i));
        pageNumbersContainer.appendChild(pageBtn);
    }

    // 最后一页按钮
    if (endPage < totalPages) {
        if (endPage < totalPages - 1) {
            const ellipsis = document.createElement('span');
            ellipsis.textContent = '...';
            pageNumbersContainer.appendChild(ellipsis);
        }

        const lastPageBtn = document.createElement('button');
        lastPageBtn.textContent = totalPages;
        lastPageBtn.addEventListener('click', () => goToPage(totalPages));
        pageNumbersContainer.appendChild(lastPageBtn);
    }

    // 更新上一页/下一页按钮状态
    prevPageBtn.disabled = currentPage === 1;
    nextPageBtn.disabled = currentPage === totalPages || totalPages === 0;
}

// 跳转到指定页
function goToPage(page) {
    currentPage = page;
    renderProducts(filteredProducts, currentPage);
}

// 高亮匹配文本
function highlightMatch(text, query) {
    if (!query) return text;

    const regex = new RegExp(query.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'gi');
    return text.replace(regex, match => `<span class="match-highlight">${match}</span>`);
}

// 显示联想建议
function showSuggestions(query) {
    if (!query) {
        suggestionsContainer.style.display = 'none';
        return;
    }

    const suggestions = productData.filter(product =>
        product.商品名称.includes(query) ||
        product.商品ID.toString().includes(query) ||
        product.商品类型.includes(query)
    ).slice(0, 5);

    if (suggestions.length === 0) {
        suggestionsContainer.style.display = 'none';
        return;
    }

    suggestionsContainer.innerHTML = suggestions.map((product, index) => `
            <div class="suggestion-item ${index === highlightedIndex ? 'highlighted' : ''}" 
                 data-index="${index}" 
                 data-id="${product.商品ID}">
                <div class="suggestion-content">
                    <div class="suggestion-title">${highlightMatch(product.商品名称, query)}</div>
                    <div class="suggestion-meta">
                        <span>ID: ${product.商品ID}</span>
                        <span>¥${product.商品售价}</span>
                        <span>库存: ${product.库存}</span>
                    </div>
                </div>
            </div>
        `).join('');
    suggestionsContainer.style.display = 'block';
}

// 选择建议项
function selectSuggestion(index) {
    const items = suggestionsContainer.querySelectorAll('.suggestion-item');
    if (items.length === 0) return;

    // 移除之前的高亮
    items.forEach(item => item.classList.remove('highlighted'));

    // 处理边界情况
    if (index >= items.length) index = 0;
    if (index < 0) index = items.length - 1;

    // 添加新高亮
    items[index].classList.add('highlighted');
    highlightedIndex = index;

    // 滚动到可见区域
    items[index].scrollIntoView({
        behavior: 'smooth',
        block: 'nearest'
    });
}

// 执行搜索
function performSearch(query) {
    filteredProducts = productData.filter(product =>
        product.商品名称.includes(query) ||
        product.商品ID.toString().includes(query) ||
        product.商品类型.includes(query)
    );

    currentPage = 1; // 重置到第一页
    renderProducts(filteredProducts.length > 0 ? filteredProducts : productData);
    suggestionsContainer.style.display = 'none';
}

// 事件监听
searchInput.addEventListener('input', function() {
    const query = this.value.trim();
    highlightedIndex = -1;
    showSuggestions(query);
});

searchInput.addEventListener('keydown', function(e) {
    if (e.key === 'ArrowDown') {
        e.preventDefault();
        selectSuggestion(highlightedIndex + 1);
    } else if (e.key === 'ArrowUp') {
        e.preventDefault();
        selectSuggestion(highlightedIndex - 1);
    } else if (e.key === 'Enter') {
        const items = suggestionsContainer.querySelectorAll('.suggestion-item');
        if (items.length > 0 && highlightedIndex >= 0) {
            const selectedId = items[highlightedIndex].getAttribute('data-id');
            const selectedProduct = productData.find(p => p.商品ID == selectedId);
            searchInput.value = selectedProduct.商品名称;
            performSearch(selectedProduct.商品名称);
        } else {
            performSearch(this.value.trim());
        }
    } else if (e.key === 'Escape') {
        suggestionsContainer.style.display = 'none';
    }
});

suggestionsContainer.addEventListener('click', function(e) {
    const item = e.target.closest('.suggestion-item');
    if (item) {
        const productId = item.getAttribute('data-id');
        const selectedProduct = productData.find(p => p.商品ID == productId);
        searchInput.value = selectedProduct.商品名称;
        performSearch(selectedProduct.商品名称);
    }
});

document.addEventListener('click', function(e) {
    if (!searchInput.contains(e.target) && !suggestionsContainer.contains(e.target)) {
        suggestionsContainer.style.display = 'none';
    }
});

// 分页按钮事件
prevPageBtn.addEventListener('click', () => {
    if (currentPage > 1) {
        goToPage(currentPage - 1);
    }
});

nextPageBtn.addEventListener('click', () => {
    const totalPages = Math.ceil(filteredProducts.length / itemsPerPage);
    if (currentPage < totalPages) {
        goToPage(currentPage + 1);
    }
});
// 全选/取消全选
const headerCheckbox = document.querySelector('thead input[type="checkbox"]');
headerCheckbox.addEventListener('change', function() {
    const rowCheckboxes = document.querySelectorAll('tbody input[type="checkbox"]');
    rowCheckboxes.forEach(checkbox => {
        checkbox.checked = this.checked;
        const tr = checkbox.closest('tr');
        tr.classList.toggle('selected', checkbox.checked);
    });
});

// 行点击效果
tbody.addEventListener('click', function(e) {
    const checkbox = e.target.closest('tr')?.querySelector('input[type="checkbox"]');
    if (checkbox && !e.target.closest('button') && !e.target.closest('.status-switch')) {
        checkbox.checked = !checkbox.checked;
        const tr = checkbox.closest('tr');
        tr.classList.toggle('selected', checkbox.checked);
    }
});

// 状态切换
tbody.addEventListener('change', function(e) {
    if (e.target.matches('.status-switch input')) {
        const tr = e.target.closest('tr');
        const productId = tr.querySelector('td:nth-child(2)').textContent;
        const newStatus = e.target.checked;
        // 这里可以添加状态更新逻辑
    }
});

// 初始化渲染
renderProducts(productData);

//删除行
const btn2=document.querySelectorAll('.btn2')
btn2.forEach(function (item){
  item.ondblclick=function (){
          this.parentElement.parentElement.parentElement.remove()
  }
})
// 编辑
const btn1=document.querySelectorAll('.btn1')
const pop=document.querySelector('.pop')
btn1.forEach(function (item){
    item.onclick=function (){
        pop.style.display = 'block';
    }
})
const span=document.querySelector('.pop span')
 span.onclick=function(){
    pop.style.display = 'none';
 }
